import 'command_item.dart';
import 'world.dart';

mixin CommandManager {
  List<CommandItem> commands = [];

  String optionCommandsDesc() {
    List<CommandItem> list = optionCommands();
    String desc = '';
    for (var item in list) {
      int index = list.indexOf(item);
      desc += '[${index+1}]${item.name} ';
    }
    return desc;
  }

  List<CommandItem> optionCommands(){
    return commands;
  }

  void add(CommandItem command) {
    commands.add(command);
  }

  /// 保持只有一个，如果已存在则不添加，如果不存在则添加
  void keepOne(CommandItem command) {
    this.removeByName(command);
    this.add(command);
  }

  void removeByName(CommandItem command) {
    commands.removeWhere((test)=>test.name==command.name);
  }

  void removeById(CommandItem command) {
    commands.removeWhere((test)=>test.id==command.id);
  }

  CommandItem commandForIndexOrName(String value) {
    int intValue;
    try {
      intValue = int.parse(value);
    } catch (e) {
      intValue = -1;
    }
    int index = intValue-1;
    var result;
    if (index>=0 && index < optionCommands().length) {
      result = optionCommands()[index];
    } else {
      result = commandForName(value);
    }
    if (result == null) {
      result = World.instance.commandForName(value);
    }
    return result;
  }

  /// 通过name或者快捷命令查找
  CommandItem commandForName(String name) {
    for (var item in optionCommands()) {
      if (item?.name == name || item?.code == name) {
        return item;
      }
    }
    return null;
  }
}